package com.jyx.manage_cms_client.service;

import com.jyx.framework.domain.cms.CmsPage;
import com.jyx.framework.domain.cms.CmsSite;
import com.jyx.framework.domain.cms.response.CmsCode;
import com.jyx.framework.exception.ExceptionCast;
import com.jyx.framework.exception.ExceptionCatch;
import com.jyx.manage_cms_client.dao.CmsPageRepository;
import com.jyx.manage_cms_client.dao.CmsSiteRepository;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;

@Service
public class PageService {
    @Autowired
    CmsPageRepository cmsPageRepository;
    @Autowired
    CmsSiteRepository cmsSiteRepository;
    @Autowired
    GridFsTemplate gridFsTemplate;
    @Autowired
    GridFSBucket gridFSBucket;

    /**
     * 将HTML保存到页面物理地址
     * @param pageId
     */
    public void savePageToServerPath(String pageId){
        //获取CmsPage并取出物理位置
        Optional<CmsPage> cmsPageOptional = cmsPageRepository.findById(pageId);
        if(!cmsPageOptional.isPresent()){
            ExceptionCast.cast(CmsCode.CMS_PAGE_NOTEXISTS);
        }
        CmsPage cmsPage = cmsPageOptional.get();
        CmsSite cmsSite = getCmsSiteById(cmsPage.getSiteId());
        //根据页面和站点获取物理地址以供下载
        //String pagePath = cmsSite.getSiteDomain()+":"+cmsSite.getSitePort()+cmsSite.getSiteWebPath() + cmsPage.getPagePhysicalPath() + cmsPage.getPageName();
        //String pagePath = cmsSite.getSiteDomain()+":"+cmsSite.getSitePort()+cmsPage.getPageWebPath()+cmsPage.getPageName();
        String pagePath = cmsPage.getPagePhysicalPath()+cmsPage.getPageName();
        String htmlFileId = cmsPage.getHtmlFileId();
        //获取输入流
        InputStream inputStream = getFileById(htmlFileId);
        if(inputStream==null){
            ExceptionCast.cast(CmsCode.CMS_GENERATEHTML_HTMLISNULL);
        }
        FileOutputStream fileOutputStream = null;
        File pageFile = new File(pagePath);
        if(!pageFile.exists()){
            try {
                pageFile.createNewFile();
            } catch (IOException e) {
                System.out.println("==============Create File failed.===================");
                e.printStackTrace();
            }
        }
        try{
            fileOutputStream = new FileOutputStream(new File(pagePath));
            IOUtils.copy(inputStream, fileOutputStream);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                inputStream.close();
            }catch (IOException e){
                e.printStackTrace();
            }
            try{
                fileOutputStream.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 根据文件Id获取文件输入流
     * @param htmlFileId
     * @return
     */
    private InputStream getFileById(String htmlFileId) {
        try{
            GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(htmlFileId)));
            GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
            GridFsResource gridFsResource = new GridFsResource(gridFSFile,gridFSDownloadStream);
            return gridFsResource.getInputStream();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据站点id得到站点
     * @param siteId
     * @return
     */
    private CmsSite getCmsSiteById(String siteId) {
        Optional<CmsSite> cmsSiteOptional = cmsSiteRepository.findById(siteId);
        if(cmsSiteOptional.isPresent()){
            CmsSite cmsSite = cmsSiteOptional.get();
            return cmsSite;
        }
        return null;
    }
}
